package service

import (
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/commonProtocol"
	"github.com/wzh200x/webServer/constants"
	Server "github.com/wzh200x/webServer/server"
)

// ServerResponse 服务器信息响应结构
type ServerResponse struct {
	Servers []ServerInfo `json:"servers"`
}

// ServerInfo 服务器信息结构
type ServerInfo struct {
	ID             int32  `json:"id"`
	CreateTime     string `json:"createTime"`
	UpdateTime     string `json:"updateTime"`
	Name           string `json:"name"`
	Zone           int32  `json:"zone"`
	ThirdZone      int32  `json:"thirdZone"`
	Address        string `json:"address"`
	Port           int32  `json:"port"`
	WebAddress     string `json:"webAddress"`
	WebPort        int32  `json:"webPort"`
	WebSsl         bool   `json:"webSsl"`
	WebSecret      string `json:"webSecret"`
	WebAddressBack string `json:"webAddressBack"`
	Status         int32  `json:"status"`
	Sort           int32  `json:"sort"`
	Description    string `json:"description"`
	OpenTime       string `json:"openTime"`
}

// GetServers 获取服务器信息
func GetServers() (*ServerResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 构建查询参数，查询所有服务器信息，不需要指定Zone
	serverQuery := commonProtocol.ServerQuery{}

	// 调用dbAgentServer获取服务器信息
	serverResp, queryErr := dbAgentClient.QueryServer(serverQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "获取服务器信息失败: " + queryErr.Error()
	}

	// 转换为响应结构
	response := &ServerResponse{
		Servers: make([]ServerInfo, 0),
	}

	// 将proto结构转换为响应结构
	if serverResp.Servers != nil {
		for _, server := range serverResp.Servers {
			if server != nil {
				serverInfo := ConvertProtoServer(server)
				response.Servers = append(response.Servers, *serverInfo)
			}
		}
	}

	return response, 0, ""
}

// ConvertProtoServer 将proto的Server转换为服务层的ServerInfo
func ConvertProtoServer(protoServer *commonProtocol.Server) *ServerInfo {
	if protoServer == nil {
		return nil
	}

	return &ServerInfo{
		ID:             protoServer.ID,
		CreateTime:     protoServer.CreateTime,
		UpdateTime:     protoServer.UpdateTime,
		Name:           protoServer.Name,
		Zone:           protoServer.Zone,
		ThirdZone:      protoServer.ThirdZone,
		Address:        protoServer.Address,
		Port:           protoServer.Port,
		WebAddress:     protoServer.WebAddress,
		WebPort:        protoServer.WebPort,
		WebSsl:         protoServer.WebSsl,
		WebSecret:      protoServer.WebSecret,
		WebAddressBack: protoServer.WebAddressBack,
		Status:         protoServer.Status,
		Sort:           protoServer.Sort,
		Description:    protoServer.Description,
		OpenTime:       protoServer.OpenTime,
	}
}
